package com.letoken.platform.admin.controller;

import com.letoken.platform.admin.util.EnumUploadType;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.UUIDUtil;
import com.letoken.platform.repo.awss3.service.AWSS3Service;
import com.letoken.platform.repo.mall.dao.AppMallMenuConfigMapper;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
public class AdminUploadController {

    @Autowired
    private AWSS3Service aWSS3Service;


    @NotAuthorization
    @PostMapping(value = "/uploadImage")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @ApiImplicitParams({ @ApiImplicitParam(dataType = "MultipartFile", name = "file", value = "文件", required = true),
            @ApiImplicitParam( dataType = "Integer", name = "businessType", value = "业务类型1=商城分类 2=token 3=mall_banner", required = true)
    })
    public ApiResponse uploadImage(@RequestParam("file") MultipartFile file,
                                   @RequestParam("businessType") Integer businessType) {
        if (file.isEmpty()) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_USER_012);
        }
        EnumUploadType enumUploadType =  EnumUploadType.getType(businessType);


        boolean flag = false;
        //校验文件类型
        List<String> imageTypeList = new ArrayList<>();
        imageTypeList.add("jpg");
        imageTypeList.add("jpeg");
        imageTypeList.add("png");
        imageTypeList.add("webp");
        for (String imageType : imageTypeList) {
            if (StringUtils.endsWithIgnoreCase(Objects.requireNonNull(file.getOriginalFilename()), imageType)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            String key = enumUploadType.getDir() + UUIDUtil.getUUID(16);
            String url = aWSS3Service.uploadFile(file, key);
//            if (!StringUtils.isNullOrEmpty(url)){
//                int index = url.indexOf("/" + key);
//                if (index > 0)
//                    url = url.substring(index);
//            }
            return ApiResponse.create(url);
        } else{
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_USER_013);
        }
    }

}
